<script setup lang="ts">
import type { ComponentExposed } from 'vue-component-type-helpers'
import { Delete } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import RecalculationForm from './RecalculationForm.vue'
import type {
  CustomDialogInstance,
  TableColumn,
} from '@/types'
import { calculationIndicatorRecalculationApi } from '@/api'
// ------------------use------------------
// #region
const props = defineProps<{
  selectData: any | null
}>()
const emits = defineEmits<{
  success: []
}>()
const { $message, $confirm } = useCurrentInstance()
const [tableData, setTableData] = useState<any[]>([])
const [isEdit, setIsEdit] = useState(false)
const [selectOptions, setSelectOptions] = useState<any[]>(
  [],
)
const [info, setInfo] = useState<
  Record<string, { type: number, formulaContent: string }>
>({})
const [currentInfo, setCurrentInfo] = useState<{
  type: number
  formulaContent: string
}>({ type: 0, formulaContent: '' })
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<any>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '指标名称',
    render() {
      return props.selectData.indicatorName
    },
  },
  {
    key: uuid(),
    label: '指标编码',
    render() {
      return props.selectData.indicatorNumber
    },
  },
  {
    key: uuid(),
    label: '时间类型',
    render({ row }) {
      const item = selectOptions.value.find(
        item => item.dicKey === row.key,
      )!
      return item.dicValue
    },
  },
  {
    key: uuid(),
    label: '重算时间',
    render({ row }) {
      return `${row.startTime} 至 ${row.endTime}`
    },
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const dialogRef = ref<CustomDialogInstance | null>(null)
const formRef
  = ref<ComponentExposed<typeof RecalculationForm>>()
// #endregion
// ------------------reactive------
// #region
// #endregion
// ------------------computed------
// #region
const options = computed(() => {
  const keys = tableData.value.map(item => item.key)
  return selectOptions.value.filter(
    item => !keys.includes(item.dicKey),
  )
})
// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function open() {
  dialogRef.value?.open?.()
  await nextTick()
  dialogRef.value?.setSaving?.(false)
  getOptions()
  getInfo()
  setCurrentInfo({ type: 0, formulaContent: '' })
}
async function close() {
  setIsEdit(false)
  await nextTick()
  dialogRef.value?.close?.()
  await nextTick()
  setTableData([])
  formRef.value?.reset?.()
}
async function add() {
  const isValid = await formRef.value?.validate?.()
  if (!isValid)
    return
  const formData = await formRef.value?.getData?.()!

  setTableData([...tableData.value, formData])
  setIsEdit(true)
  formRef.value?.reset?.()
}
async function remove(index: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  tableData.value.splice(index, 1)
  $message.success('删除成功')
  setIsEdit(true)
}
function handleBeforeClose(done: () => void) {
  if (isEdit.value) {
    $confirm('数据未保存，确定关闭？', '警告', {
      type: 'warning',
    }).then(() => {
      done()
      setIsEdit(false)
      setTableData([])
    })
  }
  else {
    done()
    setIsEdit(false)
    setTableData([])
  }
}
async function getOptions() {
  const { data } = await sysDictionaryEncoApi.queryList(
    'SHI_JIAN_KE_LI',
  )
  setSelectOptions(data)
}
async function clickSave(done: () => void) {
  try {
    await addOrUpdateData()
    done()
    emits('success')
    close()
    $message.success('重新计算已发起！')
  }
  catch (error) {
    done()
  }
}
async function addOrUpdateData() {
  const { indicatorName, indicatorNumber }
    = props.selectData!
  const arr = tableData.value.map(item => ({
    indicatorName,
    indicatorNumber,
    ...item,
  }))
  await calculationIndicatorRecalculationApi.batchIndicatorRecalculation(
    arr,
  )
}
async function getInfo() {
  const { data: res }
    = await calculationIndicatorRecalculationApi.selectFormulaContentByIndicatorNumber(
      props.selectData.indicatorNumber!,
    )
  setInfo(res)
}
async function handleKeyChange() {
  const formData = await formRef.value?.getData?.()!
  setCurrentInfo(unref(info)[formData.key]!)
}
// #endregion
defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="发起重算"
    need-saving
    width="900px"
    :before-close="handleBeforeClose"
    @confirm="clickSave"
  >
    <div class="height-vh-1/2 flex container">
      <DelayRenderGroup>
        <DelayRender>
          <view-table
            :show-toolbox="false"
            :columns="columns"
            :data="tableData"
            class="flex-sub !height-fill"
          >
            <template #operate="{ index }">
              <TdButton
                title="删除"
                :icon="Delete"
                type="danger"
                @click="remove(index)"
              />
            </template>
          </view-table>
        </DelayRender>
        <DelayRender>
          <div class="flex-sub margin-left-sm height-fill">
            <p>
              指标名称:
              <span class="margin-left-xs">
                {{ selectData.indicatorName }}
              </span>
            </p>
            <p
              class="text-overflow-hide"
              :title="selectData.indicatorNumber ?? ''"
            >
              指标编码:
              <span class="margin-left-xs">
                {{ selectData.indicatorNumber }}
              </span>
            </p>
            <p>
              公式类型:
              <el-tag size="small" class="margin-left-xs">
                {{
                  typeof currentInfo?.type === 'number'
                    ? currentInfo.type === 0
                      ? '无'
                      : currentInfo.type === 1
                        ? '录入'
                        : currentInfo.type === 2
                          ? '计算公式'
                          : '统计公式'
                    : '---'
                }}
              </el-tag>
            </p>
            <div
              v-if="[3, 4].includes(currentInfo?.type ?? 0)"
              class="flex"
            >
              <span
                class="flex-incompressible"
                style="white-space: nowrap"
              >
                计算公式:
              </span>
              <div
                class="overflow flex-fillRemaining padding-xs margin-left-xs code"
              >
                {{ currentInfo?.formulaContent ?? '---' }}
              </div>
            </div>
            <fieldset
              class="flex-direction margin-0 !margin-top-sm flex align-end"
            >
              <legend class="padding-lr-sm text-bold">
                任务配置
              </legend>
              <RecalculationForm
                ref="formRef"
                :select-options="options"
                @key-change="handleKeyChange"
              />
              <el-button
                plain
                type="primary"
                class="width-max-content"
                @click="add"
              >
                新增
              </el-button>
            </fieldset>
          </div>
        </DelayRender>
      </DelayRenderGroup>
    </div>
  </CustomDialog>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
.code {
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  color: var(--el-text-color-regular);
}
//-------------样式穿透-------------
</style>
